<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="用户昵称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.username" placeholder="用户账号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" @click="handleFilter">
        <svg-icon icon-class="search" /> 搜索
      </el-button>
      <el-button v-permission="['p_user_insert']" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">
        <svg-icon icon-class="add" /> 添加
      </el-button>
      <el-button v-permission="['p_user_delete']" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleDelete">
        <svg-icon icon-class="delete-lot-row" /> 多行删除
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      ref="multipleTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-key="getRowKey"
      @sort-change="sortChange"
    >
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true"
      />
      <el-table-column label="用户昵称" align="center" sortable="custom" prop="name" :class-name="getSortClass('name')">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户账号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['p_user_delete', 'p_user_update', 'p_role_retsetPassword', 'p_user_pickUpRole'])" label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button v-permission="['p_user_update']" type="primary" circle @click="handleUpdate(row)">
              <svg-icon icon-class="edit" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="重置密码" placement="top">
            <el-button v-permission="['p_role_retsetPassword']" type="primary" circle @click="handleReSetPassword(row)">
              <svg-icon icon-class="resetPassword" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
            <el-button v-permission="['p_user_pickUpRole']" type="primary" circle @click="handlePickUpRoles(row)">
              <svg-icon icon-class="update-roles" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button v-permission="['p_user_delete']" type="danger" circle @click="handleDeleteColumn(row)">
              <svg-icon icon-class="delete" />
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="closeOnClickModal">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <pick-up-role :visible="dialogRoleVisible" :uuid="uuid" @dialogData="closeDialog" />
  </div>
</template>

<script>
import { selectUserPage, insertUser, updateUser, deleteUser, validUsername, resetPassword } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import pickUpRole from './components/pickUpRole'
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'User',
  components: { Pagination, pickUpRole },
  directives: { waves },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('请输入账号'))
      }
      const user = { uuid: '', username: value }
      if (this.dialogStatus === 'update') {
        user.uuid = this.temp.uuid
      }
      validUsername(user).then(response => {
        if (!response.data) {
          callback(new Error('此账号已经被人使用了啦'))
        } else {
          callback()
        }
      }).catch(err => {
        callback(new Error(err))
      })
    }
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        username: '',
        ids: [],
        sort: 'asc'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      temp: {
        uuid: '',
        name: '',
        username: ''
      },
      uuid: '',
      dialogFormVisible: false,
      dialogRoleVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      rules: {
        name: [{ required: true, message: '请输入您的名称', trigger: 'blur' }],
        username: [{ required: true, trigger: 'change', validator: validateUsername }]
      },
      downloadLoading: false,
      closeOnClickModal: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      selectUserPage(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getRowKey(row) {
      return row.uuid
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReSetPassword(row) {
      this.$confirm('确定重置该用户的密码吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await resetPassword(row)
          this.getList()
          this.$message({
            type: 'success',
            message: '重置成功！'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleDeleteColumn(row) {
      const data = { ids: [] }
      const ids = []
      ids.push(row.uuid)
      data.ids = ids
      this.$confirm('确定删除该用户吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const response = await deleteUser(data)
          this.getList()
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.data
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    handlePickUpRoles(row) {
      this.uuid = row.uuid
      this.dialogRoleVisible = true
    },
    closeDialog(data) {
      this.dialogRoleVisible = data// 子组件触发父组件事件，进行数据变更，同步result数据
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'name') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'asc'
      } else {
        this.listQuery.sort = 'desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        uuid: '',
        name: '',
        username: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          insertUser(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.password = null
          updateUser(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete() {
      const data = { ids: [] }
      const colmuns = this.$refs.multipleTable.selection
      if (colmuns.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择一行用户数据！'
        })
        return
      }
      colmuns.forEach(colmun => {
        data.ids.push(colmun.uuid)
      })
      this.$confirm('确定删除这些用户吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const response = await deleteUser(data)
          this.getList()
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.data
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style scoped lang="scss">
.show-pwd {
    position: absolute;
    right: 10px;
    top: 1px;
    cursor: pointer;
    user-select: none;
  }
</style>
